<template>
  <div class="login-container">
    <van-nav-bar title="登录" left-text="返回" left-arrow>
      <template #left>
        <img src="@/assets/image/logo.png" class="logo" alt="" />
      </template>
    </van-nav-bar>
    <van-form @submit="onSubmitFn">
      <van-field
        v-model="formLogin.mobile"
        type="tel"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="[
          {
            required: true,
            message: '请填写合法手机号',
            trigger: 'onChange',
            pattern: /^1[3456789]\d{9}$/,
          },
        ]"
      />
      <van-field
        v-model="formLogin.code"
        type="password"
        label="密码"
        placeholder="请输入密码"
        required
        :rules="[
          {
            required: true,
            message: '请填验证码',
            trigger: 'onChange',
            pattern: /^\d{6}$/,
          },
        ]"
      />
      <div style="margin: 16px">
        <van-button
          :loading="loading"
          loading-text="正在登录..."
          block
          type="info"
          native-type="submit"
        >
          登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// 按需引入
import { loginAPI } from '@/api/login'
// 按需导入mapmutations
import { mapMutations } from 'vuex'
// 导入用户登录时弹出提示信息
import { Notify } from 'vant'
export default {
  name: 'Login',
  data () {
    return {
      loading: false,
      formLogin: {
        mobile: '13888888888',
        code: '246810' // 默认只能用246810后台规定了
      }
    }
  },
  methods: {
    // 调用mutation方法,把token储存到vuex中
    ...mapMutations('user', ['setToken', 'setRefreshToken']),
    async onSubmitFn () {
      //  点击按钮时立即加载
      this.loading = true
      try {
        // 调用接口拿数据
        const res = await loginAPI(
          {
            tel: this.formLogin.mobile,
            pwd: this.formLogin.code
          })
        const { token, refresh_token: refreshToken } = res.data.data
        this.setToken(token)
        this.setRefreshToken(refreshToken)
        Notify({ type: 'success', message: '登录成功' })
        this.$router.push('/layout')
        // 数据请求完毕后停止加载
        this.loading = false
      } catch (err) {
        Notify({ type: 'warning', message: '手机号或密码错误' })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.logo {
  width: 100px;
  height: 30px;
}
</style>
